package com.cgy.utils.base.dynamic;

import com.cgy.utils.base.dynamic.handler.AgencyHandler;
import com.cgy.utils.base.dynamic.handler.AgencyOptimize;

/**
 * 代理
 * @author CH
 */
public class AgencyHelper<T> {

    private Class<?> agencyClass;

    private DynamicInterceptor<T> dynamicInterceptor;

	private T t;

    protected AgencyHelper(){}

    public AgencyHelper(Class<T> agencyClass) {
        this.agencyClass = agencyClass;
        this.dynamicInterceptor = new DynamicInterceptor<T>(this.agencyClass, null, null);
    }

    public AgencyHelper(Class<T> agencyClass, AgencyHandler agencyOptimize) {
        this.agencyClass = agencyClass;
        this.dynamicInterceptor = new DynamicInterceptor<T>(this.agencyClass, null, agencyOptimize);
    }

    public AgencyHelper(Class<T> agencyClass, ClassLoader classLoader, AgencyHandler agencyOptimize) {
        this.agencyClass = agencyClass;
        this.dynamicInterceptor = new DynamicInterceptor<T>(this.agencyClass, classLoader, agencyOptimize);
    }

    /**
     * 初始化
     * @return
     */
    public static <T>AgencyHelper<T> newAgency(Class<T> agencyClass) {
        return new AgencyHelper<T>(agencyClass);
    }
    /**
     * 初始化
     * @return
     */
    public static <T>AgencyHelper<T> newAgency(Class<T> agencyClass, AgencyHandler agencyHandler) {
    	return new AgencyHelper<T>(agencyClass, agencyHandler);
    }
    /**
     * 初始化
     * @return
     */
    public static <T>AgencyHelper<T> newAgency(T agencyClass, AgencyHandler agencyHandler) {
    	return new AgencyHelper<T>((Class<T>)agencyClass.getClass(), agencyHandler);
    }
    /**
     * 初始化
     * @return
     */
    public static <T>AgencyHelper<T> newAgency(Class<T> agencyClass, ClassLoader classLoader) {
        return new AgencyHelper<T>(agencyClass, classLoader, null);
    }
    /**
     * 初始化
     * @return
     */
    public static <T>AgencyHelper<T> newOptimizeAgency(Class<T> agencyClass) {
        return new AgencyHelper(agencyClass, new AgencyOptimize());
    }
    /**
     * 初始化
     * @return
     */
    public static <T>AgencyHelper<T> newOptimizeAgency(T agencyObject) {
    	return new AgencyHelper<T>((Class<T>)agencyObject.getClass(), new AgencyOptimize());
    }


    /**
     * 代理
     * @return
     */
    public T agency() {
        this.t = this.dynamicInterceptor.getT();
        return t;
    }
    
    public void destroy() {
    	if(null != this.t) {
    		this.t = null;
    	}
    }
}
